<?php
namespace App\Admin\Controllers\OverSeasBa;

use App\Importer\Inventory\CNImporter;
use App\Models\Basics\SysPlatAccount;
use App\Models\OverSeasBa\RemovaleInventoryFNSku;
use App\Models\OverSeasBa\RemovaleAdjustFNSku;
use App\Models\OverSeasBa\Warehouse;
use App\Models\Product\ProductSku;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class RemovaleAdjustFnSkuUploadController extends AdminController{

    protected $title = '移库库存调整';

    protected function grid()
    {
        $type = request('type');
        return view('overseas-ba.removale-adjust-fnsku-upload.index',compact('type'));
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $action = $request->get('action');
            $re = $this->{'_import'.$action}($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importUp(UploadedFile $file){
        try{
            $data = Excel::toArray(new CNImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            $userId = Admin::user()->id;
            foreach($data as $row){
                $count++;
                $_account = $row[0] ? trim($row[0]) : '';
                $_warehouse = $row[1] ? trim($row[1]) : '';
                $fnSku = $row[2] ? trim($row[2]) : '';
                $num = $row[3] ? trim($row[3]) : 0;
                if(!$_account || !$_warehouse || !$fnSku){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                $account = strtoupper($_account);
                $warehouse = strtoupper($_warehouse);
                $key = $account.'-'.$warehouse.'-'.$fnSku;
                if(!in_array($key,$arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                if(!is_numeric($num)){
                    $errors[$count] = '数量格式有误';
                    break;
                }
                if($num < 0){
                    $errors[$count] = '数量不能小于0';
                    break;
                }
                $accountId = SysPlatAccount::getIdByAccount($account);
                if(!$accountId){
                    $errors[$count] = $_account.'系统不存在';
                    continue;
                }
                $warehouseId = Warehouse::getIdByCode($warehouse);
                if(!$warehouseId){
                    $errors[$count] = $_warehouse.'系统不存在';
                    continue;
                }
                DB::beginTransaction();
                $inventory = RemovaleInventoryFNSku::query()
                    ->where('account_id',$accountId)
                    ->where('warehouse_id',$warehouseId)
                    ->where('fnsku',$fnSku)
                    ->lockForUpdate()
                    ->first();
                if(!$inventory){
                    $errors[$count] = $key.'库存不存在，请添加库存记录';
                    continue;
                }
                $tempInstant = $inventory->instant;
                $inventory->instant = $num;
                $flag = $inventory->save();
                if(!$flag){
                    DB::rollBack();
                    continue;
                }
                $adjustFNSku = RemovaleAdjustFNSku::query()->create(
                    [
                        'account_id' => $accountId,
                        'warehouse_id' => $warehouseId,
                        'psku_id' => $inventory->psku_id,
                        'fnsku' => $fnSku,
                        'b_num' => $tempInstant,
                        'a_num' => $num,
                        'auser_id' => $userId,
                        'type' => 1,
                    ]
                );
                if(!$adjustFNSku){
                    DB::rollBack();
                    continue;
                }else{
                    DB::commit();
                }
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    private function _importNew(UploadedFile $file){
        try{
            $data = Excel::toArray(new CNImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            $skuArr = [];
            $userId = Admin::user()->id;
            foreach($data as $row){
                $count++;
                $_account = $row[0] ? trim($row[0]) : '';
                $_warehouse = $row[1] ? trim($row[1]) : '';
                $fnSku = $row[2] ? trim($row[2]) : '';
                $sku = $row[3] ? trim($row[3]) : '';
                $num = $row[4] ? trim($row[4]) : 0;
                if(!$_account || !$_warehouse || !$fnSku || !$sku){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                $account = strtoupper($_account);
                $warehouse = strtoupper($_warehouse);
                $key = $account.'-'.$warehouse.'-'.$fnSku;
                if(!in_array($key,$arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                if(!is_numeric($num)){
                    $errors[$count] = '数量格式有误';
                    break;
                }
                if($num < 0){
                    $errors[$count] = '数量不能小于0';
                    break;
                }
                $accountId = SysPlatAccount::getIdByAccount($account);
                if(!$accountId){
                    $errors[$count] = $_account.'系统不存在';
                    continue;
                }
                $warehouseId = Warehouse::getIdByCode($warehouse);
                if(!$warehouseId){
                    $errors[$count] = $_warehouse.'系统不存在';
                    continue;
                }
                $reCount = RemovaleInventoryFNSku::query()
                    ->where('account_id',$accountId)
                    ->where('warehouse_id',$warehouseId)
                    ->where('fnsku',$fnSku)
                    ->count();
                if($reCount > 0){
                    $errors[$count] = $key.'系统已存在,请勿重复添加';
                    continue;
                }
                if(!array_key_exists($sku,$skuArr)){
                    $_pSkuId = ProductSku::getValueByCode($sku,'id');
                    $skuArr[$sku] = $_pSkuId ?: false;
                }
                $pSkuId = $skuArr[$sku];
                if(!$pSkuId){
                    $errors[$count] = $sku.'系统不存在';
                    continue;
                }
                DB::beginTransaction();
                $inventory = RemovaleInventoryFNSku::query()
                    ->firstOrNew([
                        'account_id' => $accountId,
                        'warehouse_id' => $warehouseId,
                        'fnsku' => $fnSku,
                        'psku_id' => $pSkuId,
                    ]);
                $inventory->instant = $num;
                $flag = $inventory->save();
                if(!$flag){
                    DB::rollBack();
                    continue;
                }
                $adjustFNSku = RemovaleAdjustFNSku::query()->create(
                    [
                        'account_id' => $accountId,
                        'warehouse_id' => $warehouseId,
                        'psku_id' => $inventory->psku_id,
                        'fnsku' => $fnSku,
                        'b_num' => 0,
                        'a_num' => $num,
                        'auser_id' => $userId,
                        'type' => 2,
                    ]
                );
                if(!$adjustFNSku){
                    DB::rollBack();
                    continue;
                }else{
                    DB::commit();
                }
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
